﻿using LiteBlog.Common.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace LiteBlog.Infrastructure
{
    public class PostInfoModelBinder : IModelBinder
    {
        private DefaultModelBinder _binder = new DefaultModelBinder();

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var postInfo = (PostInfo)_binder.BindModel(controllerContext, bindingContext);
            var modelState = bindingContext.ModelState;
            if (modelState.ContainsKey("Categories"))
                modelState["Categories"].Errors.Clear();
            var request = controllerContext.HttpContext.Request;
            var categories = request.Form.Get("Categories");
            var serializer = new JavaScriptSerializer();
            postInfo.Categories = (List<Category>)serializer.Deserialize(categories, typeof(List<Category>));
            return postInfo;
        }
    }
}